
package com.learn.project2.service.admin.storage;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.learn.project2.bean.MarketStorage;
import com.learn.project2.bean.MarketStorageExample;
import com.learn.project2.mapper.MarketStorageMapper;
import com.learn.project2.model.bo.admin.storage.StorageDeleteBO;
import com.learn.project2.model.bo.admin.storage.StorageUpdateBO;
import com.learn.project2.model.vo.admin.storage.StorageCreateVO;
import com.learn.project2.model.vo.admin.storage.StorageListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @Classname StorageServiceImpl
 * @Description
 * @author王茁
 * @Date 2022/1/7 17:09
 */
@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    MarketStorageMapper storageMapper;

    @Value("${wxfile.maclocation}")
    String macLocation;

    @Value("${wxfile.winlocation}")
    String winLocation;


    /**
     * @description: TODO 查询  本机校验
     * @author wangzhuo
     * @date 2022-01-08 10:32
     * @version 1.0
     */
    public StorageListVO list(Integer page, Integer limit, Integer key, String name, String sort, String order) {
        PageHelper.startPage(page, limit);
        // List<StorageListDetailsBO> list = storageMapper.select(sort, order,key,name);
        MarketStorageExample storageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = storageExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (key != null) {
            criteria.andKeyLike("%" + key + "%");
        }
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        storageExample.setOrderByClause(sort + "\n" + order);
        List<MarketStorage> list = storageMapper.selectByExample(storageExample);
        PageInfo<MarketStorage> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return StorageListVO.storageListVO(total, pages, limit, list);
    }

    @Override
    /**
     * @description: TODO 添加(上传图片) 本机校验
     * @author wangzhuo
     * @date 2022-01-08 10:32
     * @version 1.0
     */
    public StorageCreateVO create(MultipartFile file,String host) {
        // storageMapper.imgUpload(file);
        String originalFilename = file.getOriginalFilename();//获取原始文件名
        String[] strArray = originalFilename.split("\\.");
        int suffixIndex = strArray.length - 1;
        String suffix = strArray[suffixIndex]; //获取文件后缀名
        String type = file.getContentType(); //获取文件类型
        long size = file.getSize();     //获取文件的大小
        //生成uuid作为文件名称
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String key = uuid + "." + suffix;
        String ipConfig = "http://"+host+":8083";
        String localPath = "/storage/upload/";


        // 设置文件储存路径
        //静态资源映射mapping location
        String os = System.getProperty("os.name");
        File destFile = null;
        // 判断操作系统
        if(os.toLowerCase().startsWith("mac")){
            destFile = new File(macLocation, key);
        }else if(os.toLowerCase().startsWith("win")){
            destFile = new File(winLocation, key);
        }


       // File destFile = new File("d:/Java/spring/project2ziliao/project2/project2-pic-upload/" + key);

        // 检测是否存在目录
        if (!destFile.getParentFile().exists()) {
            //假如文件不存在即重新创建新的文件已防止异常发生
            destFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(key);
        marketStorage.setName(originalFilename);
        marketStorage.setType(type);
        marketStorage.setSize((int) size);
        marketStorage.setUrl(ipConfig + localPath + key);
        marketStorage.setAddTime(new Date());
        marketStorage.setDeleted(false);
        //添加useGeneratedKeys="true" keyProperty="employee.id"，可返回自增的主键.
        // 返回的值在插入的对象上
        int insert = storageMapper.insert(marketStorage);
        StorageCreateVO storageCreateVO = new StorageCreateVO();
        //搜索刚添加的行信息，获取id值
      /*  MarketStorageExample storageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = storageExample.createCriteria();
        criteria.andNameEqualTo(marketStorage.getKey());
        List<MarketStorage> storageList = storageMapper.selectByExample(storageExample);
        for (MarketStorage storage : storageList) {
            storageCreateVO.setId(storage.getId());
        }*/
        storageCreateVO.setId(marketStorage.getId());
        storageCreateVO.setKey(marketStorage.getKey());
        storageCreateVO.setName(marketStorage.getName());
        storageCreateVO.setType(marketStorage.getType());
        storageCreateVO.setSize(marketStorage.getSize());
        storageCreateVO.setUrl(marketStorage.getUrl());
        storageCreateVO.setAddTime(marketStorage.getAddTime().toString());
        return storageCreateVO;
    }

    @Override
    /**
     * @description: TODO 修改 本机校验
     * @author wangzhuo
     * @date 2022-01-08 10:32
     * @version 1.0
     */
    public StorageUpdateBO update(StorageUpdateBO storageUpdateBO) {
        // storageMapper.update(storageUpdateBO);
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setUpdateTime(new Date());
        marketStorage.setName(storageUpdateBO.getName());
        MarketStorageExample storageExample = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = storageExample.createCriteria();
        criteria.andIdEqualTo(storageUpdateBO.getId());
        storageMapper.updateByExampleSelective(marketStorage, storageExample);
        return storageUpdateBO;
    }

    @Override
    /**
     * @description: TODO 删除 deleted 0->1 本机校验
     * @author wangzhuo
     * @date 2022-01-08 10:33
     * @version 1.0
     */
    public int delete(StorageDeleteBO storageDeleteBO) {
        try {
            //storageMapper.delete(storageDeleteBO);
            MarketStorage marketStorage = new MarketStorage();
            marketStorage.setDeleted(true);
            MarketStorageExample storageExample = new MarketStorageExample();
            MarketStorageExample.Criteria criteria = storageExample.createCriteria();
            criteria.andIdEqualTo(storageDeleteBO.getId());
            int i = storageMapper.updateByExampleSelective(marketStorage, storageExample);
        } catch (Exception e) {
            e.printStackTrace();
            return 404;
        }
        return 200;
    }
}
